package com.mxnet.chongjin.supoman.activity;

import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.mxnet.chongjin.supoman.R;
import com.mxnet.chongjin.supoman.config.Api;
import com.mxnet.chongjin.supoman.utils.EmailCheckUtils;
import com.mxnet.chongjin.supoman.utils.LoggerUtils;
import com.mxnet.chongjin.supoman.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

public class ChangeEmailActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {
    private Context mContext;
    private LinearLayout mLinearLayout;
    private Button mButton1, mButton2;
    private EditText mEt1, mEt2;
    private TimeCount mTimeCount;
    private SharedPreferences mPreferences;
    SharedPreferences.Editor mEditor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_email);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        mContext = ChangeEmailActivity.this;
        mTimeCount = new TimeCount(60000, 1000);
        mPreferences = getSharedPreferences("supoman", MODE_PRIVATE);
        mEditor = mPreferences.edit();

        initView();
        initData();
    }

    public void initData() {

    }

    public void initView() {
        mLinearLayout = findViewById(R.id.ll_change_email);
        mLinearLayout.setOnClickListener(this);

        mButton1 = findViewById(R.id.btn_change_get_verification_code);
        mButton1.setOnClickListener(this);

        mButton2 = findViewById(R.id.btn_change_email);
        mButton2.setOnClickListener(this);

        mEt1 = findViewById(R.id.et_change_email);
        mEt1.addTextChangedListener(this);

        mEt2 = findViewById(R.id.et_change_verification_code);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_change_get_verification_code:
                mEt1.setFocusable(false);
                mEt1.setFocusableInTouchMode(false);
                OkHttpUtils.get()
                        .url(Api.URL_HEADER + Api.EMAIL_CHECKCODE)
                        .addParams("userCode", mEt1.getText().toString())
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {

                                if (!TextUtils.isEmpty(response)) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        boolean isSuccess = jsonObject.optBoolean("success");
                                        if (isSuccess) {
                                            ToastUtils.showToast(mContext, "验证码已发送！");
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
                mTimeCount.start();
                break;
            case R.id.ll_change_email:
                new Thread() {
                    public void run() {
                        try {
                            Instrumentation inst = new Instrumentation();
                            inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                break;
            case R.id.btn_change_email:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                if (!TextUtils.isEmpty(mEt1.getText()) && !TextUtils.isEmpty(mEt2.getText())) {
                    if (EmailCheckUtils.isNameAdressFormat(mEt1.getText().toString())) {
                        OkHttpUtils.get()
                                .url(Api.URL_HEADER + Api.CHANGE_EMAIL)
                                .addParams("userCode", mEt1.getText().toString())
                                .addParams("indentCode", mEt2.getText().toString())
                                .addParams("userId", mPreferences.getString("userId", ""))
                                .build().execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {
                                LoggerUtils.e("***********", response);
                                if (!TextUtils.isEmpty(response)) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        boolean isSuccess = jsonObject.optBoolean("success");
                                        if (isSuccess) {
                                            ToastUtils.showToast(mContext, "修改成功！");
                                            mEditor.putString("userCode", mEt1.getText().toString());
                                            mEditor.commit();
                                            //                                            restartApplication();
                                            Intent intent = new Intent();
                                            intent.setClass(mContext, UserInfoActivity.class);
                                            startActivityForResult(intent, 20);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                                //                                new Thread() {
                                //                                    public void run() {
                                //                                        try {
                                //                                            Instrumentation inst = new Instrumentation();
                                //                                            inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                                //                                        } catch (Exception e) {
                                //                                            e.printStackTrace();
                                //                                        }
                                //                                    }
                                //                                }.start();
                            }
                        });
                    } else {
                        ToastUtils.showToast(mContext, "邮箱格式不正确！");
                    }
                } else {
                    ToastUtils.showToast(mContext, "请完整填写！");
                }
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(mEt1.getText()) && EmailCheckUtils.isNameAdressFormat(mEt1.getText().toString())) {
            mButton1.setBackgroundColor(getResources().getColor(R.color.regist_agreement));
            mButton1.setClickable(true);
        } else {
            mButton1.setBackgroundColor(getResources().getColor(R.color.regist_button));
            mButton1.setText(getResources().getString(R.string.regist_get_verification_code));
            mButton1.setClickable(false);
        }
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mButton1.setBackgroundColor(getResources().getColor(R.color.regist_button));
            mButton1.setClickable(false);
            mButton1.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {
            mButton1.setText(getResources().getString(R.string.send_again));
            mButton1.setClickable(true);
            mButton1.setBackgroundColor(getResources().getColor(R.color.regist_agreement));
            mEt1.setFocusableInTouchMode(true);
            mEt1.setFocusable(true);
        }
    }

    private void restartApplication() {
        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }
}
